<template>
  <div>
    <el-row v-loading="loading" :gutter="20" class="mt-3" style="margin: 1%">
      <!-- 订单总数日 -->
      <el-col :span="8">
        <el-card shadow="always">
          <template #header>
            <div class="flex items-center justify-between">
              <span class="text-[var(--el-text-color-secondary)]"
                >订单总数</span
              >
              <el-tag type="success">日</el-tag>
            </div>
          </template>

          <div class="flex items-center justify-between mt-5">
            <div class="text-lg text-right">
              {{ Math.round(byDayCountOutput) }}
            </div>
            <svg-icon icon-class="product" size="2em" />
          </div>
        </el-card>
      </el-col>
      <!--订单总数月-->
      <el-col :span="8">
        <el-card shadow="always">
          <template #header>
            <div class="flex items-center justify-between">
              <span class="text-[var(--el-text-color-secondary)]"
                >订单总数</span
              >
              <el-tag type="primary">周</el-tag>
            </div>
          </template>

          <div class="flex items-center justify-between mt-5">
            <div class="text-lg text-right">
              {{ Math.round(byMonthCountOutput) }}
            </div>
            <svg-icon icon-class="visit" size="2em" />
          </div>
        </el-card>
      </el-col>
      <!--订单总数年-->
      <el-col :span="8">
        <el-card shadow="always">
          <template #header>
            <div class="flex items-center justify-between">
              <span class="text-[var(--el-text-color-secondary)]"
                >订单总数</span
              >
              <el-tag type="warning">月</el-tag>
            </div>
          </template>

          <div class="flex items-center justify-between mt-5">
            <div class="text-lg text-right">
              {{ Math.round(byYearCountOutput) }}
            </div>
            <svg-icon icon-class="users" size="2em" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row v-loading="loading" :gutter="20" style="margin: 1%">
      <el-col :span="12">
        <el-card :style="{ height: '600px' }">
          <!-- 如果数据为空，渲染 el-empty 组件 -->
          <el-empty v-if="isEmpty" description="暂无数据" />
          <!-- 否则，渲染图表 -->
          <div v-else :id="id1" class="chart-container"></div>
          <div class="block">
            <span class="demonstration">时间</span>
            <el-date-picker
              v-model="value1"
              :shortcuts="shortcuts"
              type="datetimerange"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
            />
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card :style="{ height: '600px' }">
          <!-- 如果数据为空，渲染 el-empty 组件 -->
          <el-empty v-if="isEmpty" description="暂无数据" />
          <!-- 否则，渲染图表 -->
          <div v-if="!isEmpty" :id="id2" class="chart-container"></div>
          <div v-if="!isEmpty" class="block">
            <span class="demonstration">时间</span>
            <el-date-picker
              v-model="value1"
              :shortcuts="shortcuts"
              type="datetimerange"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
            />
          </div>
          <el-radio-group v-model="radio" class="radio-group">
            <el-radio :value="1">一级分类</el-radio>
            <el-radio :value="2">二级分类</el-radio>
            <el-radio :value="3">三级分类</el-radio>
          </el-radio-group>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import * as echarts from "echarts";
import { computed } from "vue";
import { watch } from "vue";
import { defineProps, onMounted, onUnmounted, ref } from "vue";
import {
  getCategoryTotalOrder,
  getOrderTotalByTime,
  getTotalOrder,
} from "@/api/order";
const loading = ref(true);
const byDayCountOutput = ref(0);
const byMonthCountOutput = ref(0);
const byYearCountOutput = ref(0);
const radio = ref(1);
const isEmpty = ref(false);
const value1 = ref<[Date, Date]>([
  new Date(2024, 0, 1, 10, 10),
  new Date(2024, 3, 1, 10, 10),
]);
// 定义计算属性
const titleText1 = computed(() => {
  return (
    value1.value[0].toLocaleDateString() +
    " 至 " +
    value1.value[1].toLocaleDateString() +
    " 商品总订单图"
  );
});

const titleText2 = computed(() => {
  return (
    value1.value[0].toLocaleDateString() +
    " 至 " +
    value1.value[1].toLocaleDateString() +
    " 商品各分类订单图"
  );
});

const shortcuts = [
  {
    text: "Last week",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "Last month",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "Last 3 months",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];
// 定义 props，接收父组件传递的 ID
const props = defineProps({
  // 设置默认值
  id1: {
    type: String,
    default: "chart1",
  },
  id2: {
    type: String,
    default: "chart2",
  },
});

// 定义配置项
const options1 = {
  title: {
    // 设置标题文本，根据时间段value1动态改变
    text: titleText1.value,
    // 设置标题位置
    left: "center",
  },
  tooltip: {
    trigger: "axis", // 鼠标移动到折线上时触发显示数据
    formatter: (params: any) => {
      // console.log(params);
      const param = params[0];
      // 格式：日期：2021-01-01<br/>总订单数：100
      return `${param.axisValue}<br/>总订单数：${param.data}`;
    },
  },
  toolbox: {
    show: true, // 是否显示工具栏
    feature: {
      saveAsImage: { show: true }, // 保存为图片
      dataView: { show: true, readOnly: false }, // 数据视图
    },
  },
  xAxis: {
    type: "category",
    data: [], // x 轴数据
    boundaryGap: false, // 坐标轴两边留白策略
    name: "", // 设置坐标轴名称
  },
  yAxis: {
    type: "value",
    name: "销量",
  },
  series: [
    {
      data: [],
      type: "line",
      smooth: true, // 是否平滑曲线显示
      areaStyle: {},
    },
  ],
};

const options2 = {
  title: {
    text: titleText2.value,
    left: "center",
  },
  tooltip: {
    trigger: "item",
    formatter: "{a} <br/>{b} : {c} ({d}%)",
  },
  legend: {
    left: "center",
    top: "bottom",
    data: [],
    show: false,
  },
  toolbox: {
    show: true, // 是否显示工具栏
    feature: {
      saveAsImage: { show: true }, // 保存为图片
      dataView: { show: true, readOnly: false }, // 数据视图
    },
  },
  series: [
    {
      name: "订单数",
      type: "pie",
      radius: [20, 140],
      center: ["50%", "50%"],
      roseType: "area",
      itemStyle: {
        borderRadius: 5,
      },
      label: {
        show: false, // 是否显示标签
      },
      emphasis: {
        label: {
          show: true, // 是否显示标签
        },
      },
      data: [],
    },
  ],
};

// 定义图表实例
let chart1: echarts.ECharts | null = null;
let chart2: echarts.ECharts | null = null;

// 监听 value1 的变化，更新图表的标题，2个
watch(value1, () => {
  if (chart1) {
    // 打开加载动画
    loading.value = true;
    // 更新图表的标题
    chart1.setOption({
      title: {
        text: titleText1.value,
      },
    });
    // 更新图表的数据
    getTotal();
    // 关闭加载动画
    loading.value = false;
  }
  if (chart2) {
    // 打开加载动画
    loading.value = true;
    // 更新图表的标题
    chart2.setOption({
      title: {
        text: titleText2.value,
      },
    });
    // 更新图表的数据
    getCategoryTotal();
    // 关闭加载动画
    loading.value = false;
  }
});

// 监听 radio 的变化，更新图表的数据
watch(radio, () => {
  // 打开加载动画
  loading.value = true;
  getCategoryTotal();
  // 关闭加载动画
  loading.value = false;
});

// 获取数据
function getCategoryTotal() {
  // 设置请求参数
  const params = {
    startTime: value1.value[0],
    endTime: value1.value[1],
    level: radio.value,
  };
  // console.log(params);
  // 发送请求获取数据
  // 打开加载动画
  loading.value = true;
  getCategoryTotalOrder(params).then((res) => {
    if (res.data.length === 0) {
      isEmpty.value = true;
      return;
    }
    // console.log(res);
    const name: string[] = [];
    const data: any[] = [];
    // 解构获取到的数据
    for (let i = 0; i < res.data.length; i++) {
      name.push(res.data[i].name);
      data.push({ value: res.data[i].total, name: res.data[i].name });
    }
    // console.log(data);
    // 更新图表的数据
    if (chart2) {
      chart2.setOption({
        legend: {
          data: name,
        },
        series: [
          {
            data: data,
          },
        ],
      });
    }
    // 关闭加载动画
    loading.value = false;
  });
}

function getTotal() {
  const params = {
    startTime: value1.value[0],
    endTime: value1.value[1],
  };
  // console.log(params);
  // 发送请求获取数据
  // 打开加载动画
  loading.value = true;
  getTotalOrder(params).then((res) => {
    if (res.data.length === 0) {
      isEmpty.value = true;
      return;
    }
    const orderDate: string[] = [];
    const orderCount: number[] = [];
    // 解构获取到的数据
    for (let i = 0; i < res.data.length; i++) {
      orderDate.push(res.data[i].orderDate);
      orderCount.push(res.data[i].orderCount);
    }
    // 更新图表的数据
    if (chart1) {
      chart1.setOption({
        xAxis: {
          data: orderDate,
        },
        series: [
          {
            data: orderCount,
          },
        ],
      });
    }
    // 关闭加载动画
    loading.value = false;
  });
}

// 在 onMounted 钩子函数中初始化图表
onMounted(() => {
  // 打开加载动画
  loading.value = true;
  getTotal();
  getCategoryTotal();
  getOrderTotalByTime("day").then((res) => {
    byDayCountOutput.value = res.data.length;
  });
  getOrderTotalByTime("week").then((res) => {
    byMonthCountOutput.value = res.data.length;
  });
  getOrderTotalByTime("month").then((res) => {
    byYearCountOutput.value = res.data.length;
  });
  chart1 = echarts.init(document.getElementById(props.id1)!); // 初始化图表,根据 ID 获取图表容器
  chart1.setOption(options1);
  chart2 = echarts.init(document.getElementById(props.id2)!); // 初始化图表,根据 ID 获取图表容器
  chart2.setOption(options2);
  // 关闭加载动画
  loading.value = false;
  // 监听窗口大小变化，重新渲染图表
  window.addEventListener("resize", handleResize);
});

// 在 onUnmounted 钩子函数中移除窗口大小变化事件监听器
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
});

// 窗口大小变化时重新渲染图表
function handleResize() {
  if (chart1 && chart2) {
    chart1.resize();
    chart2.resize();
  }
}
</script>

<style scoped>
.chart-container {
  box-sizing: border-box;
  align-items: center; /* 让容器内容垂直居中 */
  justify-content: center; /* 让容器内容水平居中 */
  width: 100%;
  height: 400px;
}

.block {
  flex: 1;
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
}

.block:last-child {
  border-right: none;
}

.block .demonstration {
  display: block;
  margin-bottom: 20px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.radio-group {
  display: flex;
  justify-content: center; /* 让子元素水平居中 */
}
</style>
